import { defineStore } from 'pinia'
import request from '@/request'
import router from '@/router'
import { menuTreeData } from '@/mock/data.js'
import { handleLogout } from '../api/logout.js'

//https://blog.csdn.net/weixin_62897746/article/details/129124364
//https://prazdevs.github.io/pinia-plugin-persistedstate/guide/
export const useUserStore = defineStore('user', {
  // 定义状态
  state: () => ({
    routerLoaded:false,
    user: {},
    username: '',
    userId: '',
    token: '',
    roles:[],
    permissions:[],
    avatar:'',
    // 路由菜单，用来接收服务端传递过来的菜单数据
    menuTree:[]
  }),

  // 就是一种计算属性的机制，定义的是函数，使用的是属性就相当于computed
  getters:{
    isLogin(state){
      return state.token ? true : false
    },

    roleName(state){
      return state.roles && state.roles.map(r=>r.name).join(",")
    },

    permissionCode(state){
      return state.permissions &&  state.permissions.map(r=>r.code).join(",")
    }
  },

  // 定义动作
  actions: {

   /* 设置token */ 
   setToken(newtoken){
      this.token = newtoken
   },

   /* 获取token*/
   getToken(){
    return this.token
   },
   
   /* 登出*/
   async logout (){
      // 执行服务端退出
      await handleLogout()
      // 清除状态信息
      this.token = ''
      this.user = {}
      this.username = ''
      this.userId = ''
      this.role = []
      this.permissions = []
      this.menuTree = []
      // 清除自身的本地存储
      localStorage.removeItem("ksd-kva-language")
      localStorage.removeItem("kva-pinia-userstore")
      localStorage.removeItem("isWhitelist")
      // 然后跳转到登录
      router.push({ name: 'Login', replace: true })
  },

  /* 登录*/
  async toLogin(loginUser){
      // 查询用户信息，角色，权限，角色对应菜单
      const resp = await request.post("login/toLogin", loginUser,{noToken:true})
      // 这个会回退，回退登录页
      var { user ,token,roles,permissions,avatar } = resp.data
      // 登录成功以后获取到菜单信息, 这里要调用一
      this.menuTree = menuTreeData
      // 把数据放入到状态管理中
      this.user = user
      this.userId = user.id
      this.username = user.name
      this.token = token
      this.roles = roles
      this.permissions = permissions
      this.avatar = avatar
      return Promise.resolve(resp)
    }
  },
  persist: {
    key: 'kva-pinia-userstore',
    storage: localStorage,//sessionStorage
  }
})